<style lang="scss">
.ivu-modal-wrap {
  display: flex;
  align-items: center;
  justify-content: center;
  .ivu-modal{
    top: 0;
  }
}
</style>
<template>
  <div class="content">
    <Breadcrumb>
      <BreadcrumbItem to="/index">首页</BreadcrumbItem>
      <BreadcrumbItem>文章管理</BreadcrumbItem>
    </Breadcrumb>
    <Form inline :label-width="70" label-position="left" :model="search">
      <Button type="success" style="margin-right: 30px" @click="addModal = true">添加</Button>
      <FormItem label="标题">
        <Input type="text" v-model="search.title" placeholder="请输入标题检索"/>
      </FormItem>
      <FormItem label="文章描述">
        <Input type="text" v-model="search.articleDesc" placeholder="请文章描述用户名检索"/>
      </FormItem>
      <FormItem label="标签">
        <Select v-model="search.tags" multiple filterable>
          <Option v-for="item in tagList" :value="item.id" :key="item.id">{{ item.name }}</Option>
        </Select>
      </FormItem>
      <Button type="primary" style="margin-left: 30px" @click="searchClick">搜索</Button>
    </Form>
    <Table stripe row-key="id" :columns="columns" :data="data"></Table>
    <Page :current="current" :total="total" :page-size="pageSize" show-total show-sizer show-elevator :styles="{marginTop: '20px'}" @on-change="pageChange" @on-page-size-change="pageSizeChange" />
    <Modal
      v-model="modalShow"
      :title="addModal ? '添加文章' : editModal ? '修改文章' : '灵异文章'"
      cancel-text="取消"
      class-name="center-modal"
      fullscreen
      @on-visible-change="modalChange">
      <Form :model="form" :label-width="80" ref="modalForm" :rules="rules">
        <div style="display: flex;">
          <div style="flex: 7;">
            <FormItem label="文章标题" prop="title">
              <Input v-model="form.title" placeholder="请输入文章标题"/>
            </FormItem>
            <FormItem label="文章标签" prop="tags">
              <Select v-model="form.tags" multiple filterable>
                <Option v-for="item in tagList" :value="item.id" :key="item.id">{{ item.name }}</Option>
              </Select>
            </FormItem>
            <FormItem label="文章描述" prop="articleDesc">
              <Input v-model="form.articleDesc" :autosize="{ minRows: 3, maxRows: 5 }" type="textarea" placeholder="请输入文章描述"/>
            </FormItem>
          </div>
          <div style="flex: 3;">
            <FormItem label="封面" prop="imageId">
              <Input v-model="form.imageId" style="display: none;" placeholder="请选择文章封面"/>
              <img v-show="imageData.cover.link" :src="imageData.cover.link" :alt="imageData.cover.name" :title="imageData.cover.name" @click="imageData.show = true" style="height: 200px">
              <div v-show="!imageData.cover.link" style="padding: 20px 0;width: 100%;height: 200px;text-align: center;position: relative;cursor: pointer;" @click="imageData.show = true">
                <div style="position: absolute;top: 50%;left: 50%;transform: translateX(-50%) translateY(-50%);">
                  <Icon type="md-photos" size="52" style="color: #3399ff"></Icon>
                  <p>单击选择图片</p>
                </div>
              </div>
            </FormItem>
          </div>
        </div>
        <FormItem label="文章描述" prop="content">
          <mavon-editor
            :toolbars="toolbars"
            v-model="form.content"
            language="zh-CN"
            codeStyle="atelier-estuary-dark"
            style="height: 600px"
            ref="md"
            @imgAdd="imageAdd"
            @imgDel="imageDel"
          />
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="text" size="large" @click="modalShow = false">取消</Button>
        <Button type="primary" size="large" @click="submit">{{ addModal ? '添加' : editModal ? '修改' : '灵异' }}</Button>
      </div>
    </Modal>
    <Modal
      v-model="imageData.show"
      title="选择图片"
      cancel-text="取消"
      fullscreen
      class-name="center-modal"
      @on-visible-change="imageModalChange">
      <Form inline :label-width="70" label-position="left" :model="imageData.search">
        <FormItem label="图片名">
          <Input type="text" v-model="imageData.search.name" placeholder="请输入图片名检索"/>
        </FormItem>
        <FormItem label="图片类型">
          <Select v-model="imageData.search.imageType" clearable filterable placeholder="请选择图片类型检索">
            <Option v-for="v in imageData.typeData" :value="v.id" :key="v.id">{{ v.name }}</Option>
          </Select>
        </FormItem>
        <Button type="primary" style="margin-left: 30px" @click="imageSearchClick">搜索</Button>
      </Form>
      <div style="float: left" align="center">
        <div v-for="(v, i) in imageData.data" class="image-item" :class="{ 'image-item-action': i === imageData.actionIndex }" :key="v.id" @click="imageItemClick(i, v.id, v.link, v.name)">
          <img
            :src="v.link"
            :alt="v.name"
            :title="v.name"
            height="200px"
            />
          <span class="type-text">{{ v.typeName }}</span>
          <span class="name-text">{{ v.name }}</span>
        </div>
      </div>
      <Page style="clear: both;" :current="imageData.current" :total="imageData.total" :page-size="imageData.pageSize" show-total show-sizer show-elevator :styles="{ marginTop: '20px' }" @on-change="imagePageChange" @on-page-size-change="imagePageSizeChange" />
      <div slot="footer">
        <Button type="text" size="large" @click="imageData.show = false">取消</Button>
        <Button type="primary" size="large" @click="imageSelectedClick">确定</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import Vue from 'vue'
import mavonEditor from 'mavon-editor'
import 'mavon-editor/dist/css/index.css'
import { addArticle, articleList, articleTags, delArticle, getArticle, updateArticle } from '@/api/article'
import { allTag } from '@/api/tag'
import { allImageType } from '@/api/imageType'
import { delImageByPath, imageList, imageUpload } from '@/api/image'
import { uploadLogArticleUploadImgIds } from '@/api/uploadLog'
Vue.use(mavonEditor)
export default {
  name: 'Article',
  data: function () {
    return {
      columns: [
        {
          type: 'index'
        },
        {
          title: '标题',
          tooltip: true,
          key: 'title'
        },
        {
          title: '文章描述',
          tooltip: true,
          key: 'articleDesc'
        },
        {
          title: '访问量',
          key: 'views'
        },
        {
          title: '创建用户',
          key: 'userName'
        },
        {
          title: '标签',
          key: 'tagText'
        },
        {
          title: '创建时间',
          key: 'createTime'
        },
        {
          title: '更新时间',
          key: 'updateTime'
        },
        {
          title: '操作',
          key: 'action',
          align: 'center',
          width: '160px',
          render: (h, params) => {
            return h('div', [
              h('Button', {
                props: {
                  type: 'warning',
                  size: 'small'
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: () => {
                    getArticle(params.row.id).then(res => {
                      this.form = res.data.article
                      this.form.imageId = parseInt(this.form.imageId)
                    })
                    this.imageData.cover.name = params.row.imageName
                    this.imageData.cover.link = params.row.imageLink
                    articleTags(params.row.id).then(res => {
                      this.form.tags = res.data.list
                    })
                    this.editModal = true
                  }
                }
              }, '修改'),
              h('Button', {
                props: {
                  type: 'error',
                  size: 'small'
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: () => {
                    this.$Modal.confirm({
                      title: '删除提示',
                      content: '是否确认删除?',
                      okText: '确定',
                      cancelText: '取消',
                      onOk: () => {
                        delArticle(params.row.id).then(res => {
                          if (res.code === 200) {
                            this.getData()
                            this.$Message.success(res.msg)
                          }
                        })
                      }
                    })
                  }
                }
              }, '删除')
            ])
          }
        }
      ],
      data: [],
      addModal: false,
      editModal: false,
      form: {},
      rules: {
        title: [
          {
            required: true,
            type: 'string',
            message: '标题不能为空',
            trigger: 'blur'
          },
          {
            min: 1,
            max: 200,
            message: '标题长度在1-200位之间',
            trigger: 'blur'
          }
        ],
        tags: [
          {
            required: true,
            type: 'array',
            message: '标签不能为空',
            trigger: 'blur'
          }
        ],
        articleDesc: [
          {
            required: true,
            type: 'string',
            message: '文章描述不能为空',
            trigger: 'blur'
          },
          {
            min: 1,
            max: 300,
            message: '文章描述长度在1-300位之间',
            trigger: 'blur'
          }
        ],
        imageId: [
          {
            required: true,
            type: 'number',
            message: '封面不能为空',
            trigger: 'blur'
          }
        ],
        content: [
          {
            required: true,
            type: 'string',
            message: '正文内容不能为空',
            trigger: 'blur'
          }
        ]
      },
      total: 0,
      current: 1,
      pageSize: 10,
      search: {},
      tagList: [],
      imageData: {
        show: false,
        total: 0,
        current: 1,
        pageSize: 10,
        data: [],
        search: {},
        typeData: [],
        item: {},
        actionIndex: -1,
        cover: {}
      },
      toolbars: {
        bold: true, // 粗体
        italic: true, // 斜体
        header: true, // 标题
        underline: true, // 下划线
        strikethrough: true, // 中划线
        mark: true, // 标记
        superscript: true, // 上角标
        subscript: true, // 下角标
        quote: true, // 引用
        ol: true, // 有序列表
        ul: true, // 无序列表
        link: true, // 链接
        imagelink: true, // 图片链接
        code: true, // code
        table: true, // 表格
        fullscreen: true, // 全屏编辑
        readmodel: true, // 沉浸式阅读
        htmlcode: true, // 展示html源码
        help: true, // 帮助
        /* 1.3.5 */
        undo: true, // 上一步
        redo: true, // 下一步
        trash: true, // 清空
        save: true, // 保存（触发events中的save事件）
        /* 1.4.2 */
        navigation: true, // 导航目录
        /* 2.1.8 */
        alignleft: true, // 左对齐
        aligncenter: true, // 居中
        alignright: true, // 右对齐
        /* 2.2.1 */
        subfield: true, // 单双栏模式
        preview: true // 预览
      },
      articleUploadImgIds: []
    }
  },
  mounted () {
    this.getData()
    this.getImageData()
    allTag().then(res => {
      if (res.code === 200) {
        this.tagList = res.data.list
      }
    })
    allImageType().then(res => {
      this.imageData.typeData = res.data.list
    })
  },
  computed: {
    modalShow: {
      get () {
        return this.addModal || this.editModal
      },
      set (val) {
        this.addModal = this.editModal = false
      }
    }
  },
  methods: {
    getData () {
      articleList(this.search, this.current, this.pageSize).then(res => {
        this.current = res.data.page.current
        this.total = res.data.page.total
        this.data = res.data.page.records
      })
    },
    getImageData () {
      imageList(this.imageData.search, this.imageData.current, this.imageData.pageSize).then(res => {
        this.imageData.total = res.data.page.total
        this.imageData.data = res.data.page.records
        this.imageData.current = res.data.page.current
      })
    },
    modalChange (v) {
      if (!v) {
        this.$refs.modalForm.resetFields()
        this.form = {}
        this.imageData.cover = {}
        this.articleUploadImgIds = []
      }
    },
    imageModalChange (v) {
      if (!v) {
        this.imageData.item = {}
        this.imageData.actionIndex = -1
      }
    },
    imageSelectedClick () {
      if (this.imageData.item.link === undefined || this.imageData.item.link.trim() === '') return this.$Message.warning('请选择一张图片作为封面！')
      this.form.imageId = this.imageData.item.id
      this.imageData.cover.link = this.imageData.item.link
      this.imageData.cover.name = this.imageData.item.name
      this.imageData.show = false
    },
    submit () {
      this.$refs.modalForm.validate((v) => {
        if (v) {
          if (this.addModal) {
            addArticle(this.form).then(res => {
              if (res.code === 200) {
                this.uploadLogIds()
                this.getData()
                this.$Message.success(res.msg)
                this.addModal = false
              }
            })
          }
          if (this.editModal) {
            this.form.updateTime = null
            updateArticle(this.form).then(res => {
              this.uploadLogIds()
              if (res.code === 200) {
                this.getData()
                this.$Message.success(res.msg)
                this.editModal = false
              }
            })
          }
        }
      })
    },
    uploadLogIds () {
      uploadLogArticleUploadImgIds(this.articleUploadImgIds)
      this.articleUploadImgIds = []
    },
    pageChange (index) {
      this.current = index
      this.getData()
    },
    pageSizeChange (size) {
      this.current = 1
      this.pageSize = size
      this.getData()
    },
    imagePageChange (index) {
      this.imageData.current = index
      this.getImageData()
    },
    imagePageSizeChange (size) {
      this.imageData.current = 1
      this.imageData.pageSize = size
      this.getImageData()
    },
    searchClick () {
      this.current = 1
      this.getData()
    },
    imageSearchClick () {
      this.imageData.current = 1
      this.getImageData()
    },
    imageItemClick (i, id, link, name) {
      this.imageData.actionIndex = i
      this.imageData.item.id = id
      this.imageData.item.link = link
      this.imageData.item.name = name
    },
    imageAdd (pos, file) {
      const formData = new FormData()
      formData.append('file', file)
      imageUpload(formData).then(res => {
        if (res.code === 200) {
          this.$Message.success(res.msg)
          this.$refs.md.$img2Url(pos, res.data.src)
          this.articleUploadImgIds.push(res.data.fileUploadLogId)
        }
      })
    },
    imageDel (pos) {
      delImageByPath(pos[0]).then(res => {
        if (res.code === 200) {
          this.$Message.success(res.msg)
          const index = this.articleUploadImgIds.find(res.data.fileUploadLogId)
          if (index !== -1) this.articleUploadImgIds.remove(index)
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
form {
  margin-top: 20px;
}
.image-item {
  display: inline-block;
  position: relative;
  height: 200px;
  margin-right: 10px;
  margin-bottom: 50px;
  overflow: hidden;
  .type-text {
    position: absolute;
    top: 0;
    right: 0;
    background-color: rgba(0, 0, 0, .5);
    color: #FFFFFF;
    padding: 0 5px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
  .name-text {
    width: 100%;
    position: absolute;
    bottom: 0;
    left: 0;
    text-align: center;
    background-color: rgba(0, 0, 0, .5);
    color: #FFFFFF;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
  .item-but {
    text-align: right;
    button {
      margin-left: 10px;
    }
  }
}
.image-item-action {
  border: 3px solid #ff4d4d;
}
</style>
<style>
.ivu-select-dropdown {
  z-index: 1600 !important;
}
</style>
